package com.hg.library.manager;

import android.content.Context;
import android.content.Intent;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.os.Environment;
import android.util.Log;
import android.widget.Toast;

import com.hg.highglass_library.R;
import com.hg.library.config.AppInfoConfig;
import com.hg.library.model.AppInfoModel;
import com.hg.library.utils.IoUtils;
import com.hg.library.widget.HiToast;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;

/**
 * Created by ASUS-PC on 2016/1/18.
 */
public class AppManager {

    private static final AppManager appManager = new AppManager();

    private static Context context;

    public static void init(Context context) {
        AppManager.context = context;
    }

    public static AppManager newInstance() {
        return appManager;
    }

    public static AppManager newInstance(Context context){
        init(context);
        return newInstance();
    }

    private int order;

    public List<AppInfoModel> getAppInfos() {
        List<AppInfoModel> modleList = new ArrayList<>();
        PackageManager manager = context.getPackageManager();
        List<PackageInfo> infoList = manager.getInstalledPackages(0);
        for (PackageInfo i : infoList) {

            PackageInfo info = i;
            String title = info.applicationInfo.loadLabel(manager).toString();
            String package_name = info.packageName;

            //应用过滤 根据包名
            if (AppInfoConfig.filterApp.contains(package_name)) continue;

            int versionCode = info.versionCode;
            if (manager.getLaunchIntentForPackage(package_name) == null) {
                continue;
            }
            String intentUri = manager.getLaunchIntentForPackage(package_name).toUri(0);
            long install_time = info.firstInstallTime;
            Bitmap bitmap = null;
            try {
                bitmap = ((BitmapDrawable) (manager.getApplicationIcon(package_name))).getBitmap();
            } catch (PackageManager.NameNotFoundException e) {
            }

            String sourceDir = info.applicationInfo.sourceDir;
            int length = (int) new File(sourceDir).length();
            float size = (float) (Math.floor(length / 1024f / 1024 * 100) / 100);

            if (AppInfoConfig.orderApp.contains(package_name)) {
                install_time = order++;
            }

            if (package_name.equals("com.android.letv.browser")) {
                bitmap = BitmapFactory.decodeResource(context.getResources(), R.drawable.letv_icon);
                if ("zh".equals(context.getResources().getConfiguration().locale.getLanguage())){
                    title = "浏览器";
                }
            }

            AppInfoModel infoModel = new AppInfoModel();

            infoModel.fileLength = length;
            infoModel.fileSizeM = size;
            infoModel.title = title;
            infoModel.appPkgName = package_name;
            infoModel.intentUri = intentUri;
            infoModel.installTime = install_time;
            infoModel.bitmapLogo = bitmap;
            infoModel.versionCode = versionCode;
            infoModel.isSystemApp = isSystemApp(i);

            filterApp(infoModel);

            modleList.add(infoModel);
        }

        Collections.sort(modleList);

        return modleList;
    }

    public List<AppInfoModel> getAppInfosForSecurty() {
        List<AppInfoModel> modleList = new ArrayList<>();
        PackageManager manager = context.getPackageManager();
        List<PackageInfo> infoList = manager.getInstalledPackages(0);
        for (PackageInfo i : infoList) {

            PackageInfo info = i;
            if (isSystemApp(info) || isSystemUpdateApp(info)) {
                continue;
            }
            String title = info.applicationInfo.loadLabel(manager).toString();
            String package_name = info.packageName;
            int versionCode = info.versionCode;
            long install_time = info.firstInstallTime;
            Drawable bitmap = null;
            try {
                bitmap = manager.getApplicationIcon(package_name);
            } catch (PackageManager.NameNotFoundException e) {
            }

            String sourceDir = info.applicationInfo.sourceDir;
            int length = (int) new File(sourceDir).length();
            float size = (float) (Math.floor(length / 1024f / 1024 * 100) / 100);

            if (AppInfoConfig.orderApp.contains(package_name)) {
                install_time = order++;
            }

            AppInfoModel infoModle = new AppInfoModel();

            infoModle.fileLength = length;
            infoModle.fileSizeM = size;
            infoModle.title = title;
            infoModle.appPkgName = package_name;
            infoModle.installTime = install_time;
            infoModle.drawable = bitmap;
            infoModle.versionCode = versionCode;
            infoModle.isSystemApp = isSystemApp(i);
            filterApp(infoModle);

            modleList.add(infoModle);
        }

        Collections.sort(modleList);

        return modleList;
    }

    private static final String TAG = "AppManager";

    private void filterApp(AppInfoModel infoModel) {
        String packname = infoModel.appPkgName;
        for (Map.Entry<String, Integer> entry : filterMap.entrySet()) {
            if (packname.equals(entry.getKey())) {
                infoModel.bitmapLogo = BitmapFactory.decodeResource(context.getResources(), entry.getValue());
            }
        }
    }

    private Map<String, Integer> filterMap = new HashMap<String, Integer>() {
        {
            put("com.qiyi.video", R.drawable.app_ai_qi_yi);
            put("com.hijing.securitycenter", R.drawable.app_safe_center);
            put("com.moretv.android", R.drawable.app_dian_shi_mao_shi_pin);
            put("com.moretv.mv", R.drawable.app_dian_shi_mao_yin_yue);
            put("com.duomi.androidtv", R.drawable.app_duo_mi);
            put("tv.fs.browser", R.drawable.app_fei_shi);
            put("com.tongyong.xxbox", R.drawable.app_hifi);
            put("cn.kuwo.sing.tv", R.drawable.app_ku_wo);
            put("com.starcor.mango", R.drawable.app_mang_guo);
            put("com.tencent.qqmusictv", R.drawable.app_qq_yinyue);
            put("com.ktcp.video", R.drawable.app_teng_xun);
            put("net.myvst.v2", R.drawable.app_vst);
            put("st.com.xiami", R.drawable.app_xiao_mi);
            put("com.cibn.tv", R.drawable.app_you_ku);
            put("com.hotcast.vr", R.drawable.app_hotcast);
        }
    };

    public Intent getAppIntent(String package_name) {
        Intent intent = null;
        try {
            intent = Intent.parseUri(getAppUri(package_name), 0);
        } catch (URISyntaxException e) {
            e.printStackTrace();
        }
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        return intent;
    }

    public AppInfoModel getAppInfo(String pack_name, int flag) {

        PackageManager manager = context.getPackageManager();
        try {
            PackageInfo info = manager.getPackageInfo(pack_name, flag);
            String title = info.applicationInfo.loadLabel(manager).toString();
            String package_name = info.packageName;

            int versionCode = info.versionCode;

            String intentUri = null;

            if (manager.getLaunchIntentForPackage(package_name) != null){
                intentUri = manager.getLaunchIntentForPackage(package_name).toUri(0);
            }

            long install_time = info.firstInstallTime;
            Bitmap bitmap = null;
            try {
                bitmap = ((BitmapDrawable) (manager.getApplicationIcon(package_name))).getBitmap();
            } catch (PackageManager.NameNotFoundException e) {
            }

            String sourceDir = info.applicationInfo.sourceDir;
            int length = (int) new File(sourceDir).length();
            float size = (float) (Math.floor(length / 1024f / 1024 * 100) / 100);

            if (AppInfoConfig.orderApp.contains(package_name)) {
                install_time = order++;
            }

            AppInfoModel infoModel = new AppInfoModel();

            infoModel.fileLength = length;
            infoModel.fileSizeM = size;
            infoModel.title = title;
            infoModel.appPkgName = package_name;
            infoModel.intentUri = intentUri;
            infoModel.installTime = install_time;
            infoModel.bitmapLogo = bitmap;
            infoModel.versionCode = versionCode;
            infoModel.isSystemApp = isSystemApp(info);

            return infoModel;
        } catch (PackageManager.NameNotFoundException e) {
            Log.e(TAG, "getAppInfo: " + e.getMessage());
        }
        return null;
    }

    public String getAppUri(String package_name) {
        String intentUri = context.getPackageManager().getLaunchIntentForPackage(package_name).toUri(0);
        return intentUri;
    }

    public boolean isSystemApp(PackageInfo pInfo) {
        return ((pInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0);
    }

    public boolean isSystemUpdateApp(PackageInfo pInfo) {
        return ((pInfo.applicationInfo.flags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0);
    }

}
